package yang.yu.sunny.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.dayatang.domain.AbstractEntity;
import org.dayatang.domain.InstanceFactory;
import yang.yu.sunny.EventBus;

import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Optional;

/**
 * 客户
 * Created by yyang on 16/3/15.
 */
@Entity
@Table(name = "customers")
public class Customer extends AbstractEntity {

    private String name;

    private String province;

    private String address;

    protected Customer() {
    }

    public Customer(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void changeName(String newName) {
        String oldName = name;
        name = newName;
        save();
        InstanceFactory.getInstance(EventBus.class)
                .post(new CustomerNameChangedEvent(getId(), oldName, newName));
    }

    public static Optional<Customer> get(Long customerId) {
        return Optional.ofNullable(getRepository().get(Customer.class, customerId));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (!(o instanceof Customer)) {
            return false;
        }

        Customer customer = (Customer) o;

        return new EqualsBuilder()
                .append(getName(), customer.getName())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .appendSuper(super.hashCode())
                .append(getName())
                .toHashCode();
    }
}
